<template>
  <div>
    <div>
      <template v-for="(item, index) in formInfo" :key="index">
        <button @click="formInfoClick(item)">{{ item.name }}</button>
      </template>
    </div>
  </div>
  <div>
    <!-- 如果formData为空, 则显示空状态 -->
    <template v-if="JSON.stringify(formData) === '{}'">
      <ElEmpty description="请选择模板" />
    </template>

    <!-- 如果formData不为空, 则显示表单 -->
    <template v-else>
      <EditForm :formData="formData" @submit="submit" />
    </template>
  </div>
  <div style="height: 50px"></div>
</template>

<script setup lang="ts">
import type { IFormData, IFormInfo } from '../../components/EditForm/commonType'
import formInfo1 from './JsonEditViewData/data1'
import formInfo2 from './JsonEditViewData/data2'
import formInfo3 from './JsonEditViewData/data3'
import { ref } from 'vue'
import { ElMessageBox } from 'element-plus'
import EditForm from '@/components/EditForm/EditForm.vue'

//#region webview 函数

const webViewGetFormData = () => {
  if (import.meta.env.DEV) {
    return
  }

  if (!window?.webview) {
    // El 弹出框提示
    ElMessageBox.alert('请在PDA端操作', {
      confirmButtonText: '确定',
      showClose: false,
    })
  } else {
    window.webview.raiseEvent('getFormData')
  }
}

const webViewSubmit = (jsonData: IFormData) => {
  if (!window?.webview) {
    // El 弹出框提示
    ElMessageBox.alert('请在PDA端操作', {
      confirmButtonText: '确定',
      showClose: false,
    })
  } else {
    window.webview.raiseEvent('submit', JSON.stringify(jsonData))
  }
}

//#endregion

// (初始化时) 获取表单数据, 让 webview 调用 setFormData 方法
webViewGetFormData()

const formData = ref<IFormData>({})
// 设置表单数据
window.setFormData = (json: string) => {
  formData.value = JSON.parse(json)
}

const deepClone = (data: Object) => JSON.parse(JSON.stringify(data))

const formInfo = [formInfo1, formInfo2, formInfo3]
formData.value = deepClone(formInfo[2].data)

const formInfoClick = (info: IFormInfo) => {
  formData.value = deepClone(info.data)
}

// 提交
const submit = (data: IFormData) => {
  // 开发环境打印数据
  if (import.meta.env.DEV) console.log('data', data)

  // 提交到 webview
  webViewSubmit(data)
}
</script>

<style>
:root {
  * {
    --el-color-primary: rgb(197, 34, 37);
    --el-color-primary-light-3: rgb(197, 34, 37, 0.5);
    --el-color-primary-dark-2: rgb(197, 34, 37, 0.7);
  }
}
</style>
